package users;

import avenue.MyWindowEvent;
import avenue.Session;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.AppUser;
import model.DBManager;


import java.util.*;
import javax.persistence.Query;
import model.Station;

/**
 *
 * @author Aggelos
 */
public class ListUsersForm extends javax.swing.JFrame
{

    AppUser u;
    EntityManager em;
    JFrame thisFrame;
    int s;

    /**
     * Creates new form ListUsersForm
     */
    public ListUsersForm()
    {
        em = DBManager.em;
        if (!em.getTransaction().isActive())
          {
            em.getTransaction().begin();
          }
        initComponents();
        setLocationRelativeTo(null);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        selectAppUsersByStationQUERY = em.createQuery("select au from AppUser au where au.stationId=:station").setParameter("station",Session.loginUser.getStationId());
        appUsersByStationLIST = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(selectAppUsersByStationQUERY.getResultList());
        editUserButton = new javax.swing.JButton();
        deleteUserButton = new javax.swing.JButton();
        newUserButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        usersTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        saveAndBackButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        saveButton = new javax.swing.JButton();
        statusLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        editUserButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editUserButton.setText("Επεξεργασία");
        editUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editUserButtonActionPerformed(evt);
            }
        });

        deleteUserButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteUserButton.setText("Διαγραφή");
        deleteUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteUserButtonActionPerformed(evt);
            }
        });

        newUserButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        newUserButton.setText("Νέος");
        newUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newUserButtonActionPerformed(evt);
            }
        });

        usersTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, appUsersByStationLIST, usersTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${FName}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${roleId.roleName}"));
        columnBinding.setColumnName("Ρολος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${LName}"));
        columnBinding.setColumnName("Επώνυμο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stationId.description}"));
        columnBinding.setColumnName("Σταθμός");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${userName}"));
        columnBinding.setColumnName("User Name");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${password}"));
        columnBinding.setColumnName("Password");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Address");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${city}"));
        columnBinding.setColumnName("Πόλη");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${zipCode}"));
        columnBinding.setColumnName("ΤΚ");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${phone}"));
        columnBinding.setColumnName("Τηλέφωνο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${email}"));
        columnBinding.setColumnName("Email");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${adt}"));
        columnBinding.setColumnName("ΑΔΤ");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${afm}"));
        columnBinding.setColumnName("ΑΦΜ");
        columnBinding.setColumnClass(Integer.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(usersTable);

        jLabel1.setText("Χρήστες");

        saveAndBackButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveAndBackButton.setText("Αποθήκευση Αλλαγών και Επιστροφή");
        saveAndBackButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveAndBackButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Άκυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
        jLabel2.setText("Πίνακας Χρηστών");

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση Αλλαγών");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        statusLabel.setText("Κατάσταση εγγραφών");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1110, Short.MAX_VALUE)
                            .addComponent(jSeparator1)
                            .addComponent(jSeparator2)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(newUserButton)
                                        .addGap(16, 16, 16)
                                        .addComponent(deleteUserButton)
                                        .addGap(18, 18, 18)
                                        .addComponent(editUserButton))
                                    .addComponent(jLabel2))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addGap(18, 18, 18)
                        .addComponent(saveAndBackButton)
                        .addGap(18, 18, 18)
                        .addComponent(cancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(statusLabel)
                        .addGap(40, 40, 40))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newUserButton)
                    .addComponent(deleteUserButton)
                    .addComponent(editUserButton))
                .addGap(18, 18, 18)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(53, 53, 53)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveAndBackButton)
                    .addComponent(cancelButton)
                    .addComponent(saveButton)
                    .addComponent(statusLabel))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newUserButtonActionPerformed
        // TODO add your handling code here:
        statusLabel.setText("Αλλαγές ΜΗ ΑΠΟΘΗΚΕΥΜΕΝΕΣ");
        u = new AppUser();
        em.persist(u);
        EditUserForm euf = new EditUserForm(u, false);

        euf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        //************
        euf.addWindowListener(new WindowListener()
        {
            public void windowClosed(WindowEvent arg0)
            {
                System.out.println("Window close event occur - save button clicked");
                if (((MyWindowEvent) arg0).exitAndSave)
                  {
                    appUsersByStationLIST.add(u);
                    int row = appUsersByStationLIST.size() - 1;

                    usersTable.setRowSelectionInterval(row, row);
                    usersTable.scrollRectToVisible(usersTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                  }
                else
                  {
                    System.out.println("Window close event occur -cancel button clicked");
                    thisFrame.setEnabled(true);
                    if (em.getTransaction().isActive())
                      {
                        em.getTransaction().rollback();//original
                        statusLabel.setText("Δεν υπάρχουν Αλλαγές");
                      }

                    em.getTransaction().begin();
                    java.util.Collection data = selectAppUsersByStationQUERY.getResultList();

                    for (Object entity : data)
                      {
                        em.refresh(entity);
                      }
                    appUsersByStationLIST.clear();
                    appUsersByStationLIST.addAll(data);
                  }
            }

            public void windowActivated(WindowEvent arg0)
            {
                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0)
            {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0)
            {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0)
            {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0)
            {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0)
            {
                System.out.println("Window Opened");
            }
        });
    }//GEN-LAST:event_newUserButtonActionPerformed

    private void deleteUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteUserButtonActionPerformed
        int wn = JOptionPane.showConfirmDialog(this,
                "Είστε σίγουροι ότι θέλετε να διαγράψετε τον συγκεκριμένο χρήστη",
                "Διαγραφή χρήστη",
                JOptionPane.YES_NO_OPTION);

        if (wn != 0)
          {
            return;
          }
        int s = usersTable.getSelectedRow();
        if (s >= 0)
          {
            AppUser u = appUsersByStationLIST.get(usersTable.convertRowIndexToModel(s));

            if (u == Session.loginUser)
              {
                JOptionPane.showMessageDialog(this, "Δεν μπορείς να σβήσεις ΤΟΝ ΕΑΥΤΟ ΣΟΥ!!!!!");
              }
            else
              {
                appUsersByStationLIST.remove(u);
                em.remove(u);
                statusLabel.setText("Αλλαγές ΜΗ ΑΠΟΘΗΚΕΥΜΕΝΕΣ");
              }
          }
    }//GEN-LAST:event_deleteUserButtonActionPerformed

    private void editUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editUserButtonActionPerformed
        // TODO add your handling code here:

        statusLabel.setText("Αλλαγές ΜΗ ΑΠΟΘΗΚΕΥΜΕΝΕΣ");
        s = usersTable.getSelectedRow();
       // System.out.println(s);
        if (s >= 0)
          {
            u = appUsersByStationLIST.get(usersTable.convertRowIndexToModel(s));
            em.persist(u);

            EditUserForm euf = new EditUserForm(u, false);

            euf.setVisible(true);
            thisFrame = this;
            thisFrame.setEnabled(false);

            //************
            euf.addWindowListener(new WindowListener()
            {
                public void windowClosed(WindowEvent arg0)
                {
                    System.out.println("Window close event occur");
                    if (((MyWindowEvent) arg0).exitAndSave)
                      {
                        appUsersByStationLIST.set(s, u);

                        usersTable.setRowSelectionInterval(s, s);
                        usersTable.scrollRectToVisible(usersTable.getCellRect(s, 0, true));
                        usersTable.repaint();
                        thisFrame.setEnabled(true);
                      }
                    else
                      {
                        thisFrame.setEnabled(true);
                        if (em.getTransaction().isActive())
                          {
                            em.getTransaction().rollback();
                            statusLabel.setText("Δεν υπάρχουν Αλλαγές");
                          }

                        em.getTransaction().begin();
                        java.util.Collection data = selectAppUsersByStationQUERY.getResultList();
                        for (Object entity : data)
                          {
                            em.refresh(entity);
                          }
                        appUsersByStationLIST.clear();
                        appUsersByStationLIST.addAll(data);
                      }
                }

                public void windowActivated(WindowEvent arg0)
                {
                    System.out.println("Window Activated");
                }

                public void windowClosing(WindowEvent arg0)
                {
                    System.out.println("Window Closing");
                }

                public void windowDeactivated(WindowEvent arg0)
                {
                    System.out.println("Window Deactivated");
                }

                public void windowDeiconified(WindowEvent arg0)
                {
                    System.out.println("Window Deiconified");
                }

                public void windowIconified(WindowEvent arg0)
                {
                    System.out.println("Window Iconified");
                }

                public void windowOpened(WindowEvent arg0)
                {
                    System.out.println("Window Opened");
                }
            });
          }

    }//GEN-LAST:event_editUserButtonActionPerformed

    private void saveAndBackButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveAndBackButtonActionPerformed
    {//GEN-HEADEREND:event_saveAndBackButtonActionPerformed
        em.getTransaction().commit();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_saveAndBackButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed
    {//GEN-HEADEREND:event_cancelButtonActionPerformed
        // TODO add your handling code here:

        if (em.getTransaction().isActive())
          {
            em.getTransaction().rollback();
          }
        if (!em.getTransaction().isActive())
          {
            em.getTransaction().begin();
            em.getTransaction().rollback();
          }

        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, false);
        for (WindowListener l : this.getWindowListeners())
          {
            l.windowClosed(we);
          }
        this.setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveButtonActionPerformed
    {//GEN-HEADEREND:event_saveButtonActionPerformed
        // TODO add your handling code here:
        try
          {
            if (em.getTransaction().isActive())
              {
                em.getTransaction().begin();//original
                em.getTransaction().commit();
                statusLabel.setText("Αλλαγές Αποθηκεύτηκαν");
              }

            if (!em.getTransaction().isActive())
              {

                em.getTransaction().begin();//original
                em.getTransaction().commit();
                statusLabel.setText("Αλλαγές Αποθηκεύτηκαν");
              }
          }
        catch (Exception e)
          {
            JOptionPane.showMessageDialog(this, "error in saving");
          }

    }//GEN-LAST:event_saveButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try
          {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
              {
                if ("Nimbus".equals(info.getName()))
                  {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                  }
              }
          }
        catch (ClassNotFoundException ex)
          {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (InstantiationException ex)
          {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (IllegalAccessException ex)
          {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
          {
            java.util.logging.Logger.getLogger(ListUsersForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
          }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new ListUsersForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<AppUser> appUsersByStationLIST;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deleteUserButton;
    private javax.swing.JButton editUserButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JButton newUserButton;
    private javax.swing.JButton saveAndBackButton;
    private javax.swing.JButton saveButton;
    private javax.persistence.Query selectAppUsersByStationQUERY;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JTable usersTable;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
